<template>
  <!-- 定义地图显示容器 -->
  <div id="container"></div>
</template>
<script setup>
import {
  onMounted,
  reactive,
  toRefs,
  defineEmits,
  watch,
  ref,
  onBeforeUnmount,
} from "vue";
var clickMarkerLayer = null; // 点击点标记
var map = null; // 地图
const emit = defineEmits(["mapClick"]);

const props = defineProps({
  msg: String,
  center: { type: Object, default: { lat: 28.674993, lng: 121.4077192 } },
  selectedPosition: {
    type: Object,
    default: { lat: 28.674993, lng: 121.4077192 },
  },
});

const Data = reactive({});
const {} = toRefs(Data);

onMounted(() => {
  initMap();
});
onBeforeUnmount(() => {
  map.destroy();
});
const initMap = () => {
  //定义地图中心点坐标
  var mapCenter = new TMap.LatLng(props.center.lat, props.center.lng);
  //定义map变量，调用 TMap.Map() 构造函数创建地图
  map = new TMap.Map(document.getElementById("container"), {
    center: mapCenter, //设置地图中心点坐标
    showControl: true, //显示控件
    zoom: 17.2, //设置地图缩放级别
    //pitch: 43.5, //设置俯仰角
    //rotation: 45, //设置地图旋转角度
  });
  map.on("click", (event) => {
    handleMapClick(event);
  });
};

const handleMapClick = (event) => {
  emit("mapClick", event);
  setSelectedMarker(event.latLng);
};
const setSelectedMarker = (latLng) => {
  const geometries = [
    {
      id: "1",
      styleId: "1",
      position: latLng,
      content: "当前点位",
      properties: {},
    },
  ];
  if (clickMarkerLayer) {
    clickMarkerLayer.setGeometries(geometries);
  } else {
    clickMarkerLayer = new TMap.MultiMarker({
      map: map, // 指定地图容器
      // 样式定义
      styles: {
        1: new TMap.MarkerStyle({
          width: 22,
          height: 31,
          color: "#f00",
          src: "http://minio.taishow.cc/love-umbrella/static/blank.png",
          anchor: { x: 11, y: 31 },
          direction: "top",
        }),
      },
      // 点标记数据数组
      geometries: geometries,
    });
  }
};
watch(
  () => props.selectedPosition,
  () => {
    if (map) {
      setSelectedMarker(
        new TMap.LatLng(props.selectedPosition.lat, props.selectedPosition.lng)
      );
    } else {
      initMap();
    }
  },
  { deep: true }
);
watch(
  () => props.center,
  () => {
    if (map) {
      map.setCenter(new TMap.LatLng(props.center.lat, props.center.lng));
    } else {
      initMap();
    }
  },
  { deep: true }
);
</script>
  